<?php
require_once '../db.php';
require '../vendor/autoload.php'; // 引入 Composer 自动加载器

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$secretKey = 'your_secret_key'; // 与普通用户和审核不同的密钥

if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $admin_role = $decoded->data->role;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}

if ($admin_role !== 'su_admin') {
    http_response_code(403);
    echo json_encode(["message" => "Forbidden"]);
    exit();
}


header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        // 获取所有用户
        $stmt = $conn->prepare("SELECT id, username, role FROM users");
        $stmt->execute();
        $result = $stmt->get_result(); // 获取结果集对象
        $users = [];
        while ($user = $result->fetch_assoc()) {
            $users[] = $user; // 将每行数据添加到 $users 数组中
        }
        $stmt->close(); // 关闭查询结果集
        echo json_encode($users);
        break;

    case 'POST':
        // 新增用户
        $username = $input['username'];
        $password = $input['hashedPassword'];
        $role = $input['role'];
        $stmt = $conn->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
        $stmt->execute([$username, $password, $role]);
        echo json_encode(["success" => "User added"]);
        break;

    case 'PUT':
        // 编辑用户权限
        $id = $input['id'];
        $role = $input['role'];
        $stmt = $conn->prepare("UPDATE users SET role = ? WHERE id = ?");
        $stmt->execute([$role, $id]);
        echo json_encode(["message" => "User updated"]);
        break;

    case 'DELETE':
        // 删除用户
        $id = $input['id'];
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(["message" => "User deleted"]);
        break;

    default:
        http_response_code(405);
        echo json_encode(["message" => "Method not allowed"]);
        break;
}
?>
